<template>
    <BaseEditorHeader default-active="3">
        <el-select v-model="current_page.id" allow-create filterable remote placeholder="页面列表" clearable
                   :loading="loading" @change="selectPage">
            <el-option v-for="item in allPages" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
        </el-select>
        <el-button @click="newPageDialogVisible = true">新增</el-button>
        <el-select
                v-model="platform"
                placeholder="请选择"
                :class="$style.selectPlatform"
        >
            <el-option
                    label="PC"
                    value="editor"
            ></el-option>
            <el-option
                    label="M"
                    value="editorM"
            ></el-option>
        </el-select>
        <el-button
                icon="el-icon-minus"
                :disabled="disabledMinus"
                :class="$style.scaleBtn"
                circle
                @click="handleMinus"
        >
        </el-button>
        <el-button type="text">
            {{ value }}%
        </el-button>
        <el-button
                icon="el-icon-plus"
                :disabled="disabledPlus"
                :class="$style.scaleBtn"
                circle
                @click="handlePlus"
        ></el-button>
        <el-button @click="$emit('onPreview')">预览</el-button>
        <el-button
                type="primary"
                plain
                @click="$emit('onSave')"
        >
            保存
        </el-button>
        <el-button
                type="primary"
                @click="$emit('onPublish')"
        >
            发布
        </el-button>
        <el-dropdown
                @command="handleLocalCommand"
                v-if="loginLocalAble"
                class="fr"
        >
            <el-button type="primary">
                <span class="email">{{ this.user.email  }}</span>
                <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item disabled>账号信息</el-dropdown-item>
                <el-dropdown-item disabled>文档</el-dropdown-item>
                <el-dropdown-item command="logout">退出登入</el-dropdown-item>
            </el-dropdown-menu>
        </el-dropdown>
        <el-button
                @click="localDialogVisible = true"
                v-else
                class="fr"
                type="primary"
        >本地登录
        </el-button>
        <el-dropdown
                @command="handleCommand"
                v-if="loginStoreAble"
                class="fr"
        >
            <el-button type="primary">
                <span class="email">{{ storeinfo.email }}</span>
                <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item disabled>账号信息</el-dropdown-item>
                <el-dropdown-item disabled>文档</el-dropdown-item>
                <el-dropdown-item command="logout">退出登入</el-dropdown-item>
            </el-dropdown-menu>
        </el-dropdown>
        <el-button
                @click="storeDialogVisible = true"
                v-else
                class="fr"
                type="primary"
        >登录应用市场
        </el-button>
        <el-dialog
                title="登录本地帐号"
                :visible.sync="localDialogVisible"
                width="20%"
                center
                @close="closeLocalDialog"
        >
            <el-row>
                <el-col>
                    <el-alert title="请使用本地管理后台的帐号登录" type="info" show-icon>
                    </el-alert>
                </el-col>
            </el-row>
            <el-row style="margin-top:10px">
                <el-col>
                    <el-form
                            :rules="storeFormRules"
                            label-position="top"
                            label-width="80px"
                            :model="storeForm"
                            ref="localFormRef"
                    >
                        <el-form-item prop="email">
                            <el-input
                                    prefix-icon="el-icon-user"
                                    ref="email"
                                    v-model="storeForm.email"
                                    placeholder="请输入邮箱"
                                    name="email"
                                    type="text"
                                    tabindex="1"
                                    autocomplete="on"
                            />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input
                                    prefix-icon="el-icon-lock"
                                    ref="password"
                                    show-password
                                    type="password"
                                    v-model="storeForm.password"
                                    placeholder="请输入密码"
                                    name="password"
                                    tabindex="2"
                                    autocomplete="on"
                                    @keyup.native="checkCapslock"
                                    @blur="capsTooltip = false"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleLocalForm"
                            >登录
                            </el-button
                            >
                            <el-button
                                    @click="
                  () => {
                    this.$refs.localFormRef.resetFields();
                  }
                "
                            >重置
                            </el-button
                            >
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-dialog>
        <el-dialog
                title="登录应用市场"
                :visible.sync="storeDialogVisible"
                width="20%"
                center
                @close="closeDialog"
        >
            <el-row>
                <el-col>
                    <el-alert title="请使用www.uctoo.com的帐号登录" type="info" show-icon>
                    </el-alert>
                </el-col>
            </el-row>
            <el-row style="margin-top:10px">
                <el-col>
                    <el-form
                            :rules="storeFormRules"
                            label-position="top"
                            label-width="80px"
                            :model="storeForm"
                            ref="storeFormRef"
                    >
                        <el-form-item prop="email">
                            <el-input
                                    prefix-icon="el-icon-user"
                                    ref="email"
                                    v-model="storeForm.email"
                                    placeholder="请输入邮箱"
                                    name="email"
                                    type="text"
                                    tabindex="1"
                                    autocomplete="on"
                            />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input
                                    prefix-icon="el-icon-lock"
                                    ref="password"
                                    show-password
                                    type="password"
                                    v-model="storeForm.password"
                                    placeholder="请输入密码"
                                    name="password"
                                    tabindex="2"
                                    autocomplete="on"
                                    @keyup.native="checkCapslock"
                                    @blur="capsTooltip = false"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleStoreForm"
                            >登录
                            </el-button
                            >
                            <el-button   href="https://admin.uctoo.com" target="_blank"
                            ><el-link href="https://admin.uctoo.com" type="primary" target="_blank">注册</el-link>
                            </el-button
                            >

                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-dialog>
        <el-dialog
                title="新增页面"
                :visible.sync="newPageDialogVisible"
                width="20%"
                @close="closeNewPageDialog"
        >
            <el-form
                    :rules="newPageFormRules"
                    label-position="top"
                    label-width="80px"
                    :model="newPageForm"
                    ref="newPageFormRef"
            >
                <el-form-item prop="name">
                    <el-input
                            ref="name"
                            v-model="newPageForm.name"
                            placeholder="请输入页面名称"
                            name="name"
                            type="text"
                            tabindex="1"
                            autocomplete="on"
                    />
                </el-form-item>
                <el-form-item prop="type">
                    <el-select
                            v-model="newPageForm.type"
                            placeholder="请选择"
                            :class="$style.selectPlatform"
                    >
                        <el-option
                                label="商城"
                                value="shop"
                        ></el-option>
                        <el-option
                                label="官网"
                                value="website"
                        ></el-option>
                        <el-option
                                label="表单"
                                value="form"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="platform">
                    <el-select
                            v-model="newPageForm.platform"
                            placeholder="请选择"
                            :class="$style.selectPlatform"
                    >
                        <el-option
                                label="PC"
                                value="editor"
                        ></el-option>
                        <el-option
                                label="M"
                                value="editorM"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleNewPageForm">提交</el-button>
                    <el-button @click=" () => { this.$refs.newPageFormRef.resetFields(); }">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </BaseEditorHeader>

</template>

<script>
    import BaseEditorHeader from 'demo-common/components/EditorHeader.vue';
    import {loginStore} from "../../api/user";
    import {mapGetters, mapActions} from "vuex";
    import {getToken} from '../../utils/auth';
    //import Users from '../../models/Users';

    export default {
        name: 'EditorHeader',
        data() {
            return {
                loginStatus: false,
                localDialogVisible: false,
                storeDialogVisible: false,
                newPageDialogVisible: false,
                storeForm: {},
                newPageForm: {},
                capsTooltip: false,
                storeFormRules: {
                    email: [{required: true, type: "email", trigger: "blur"}],
                    password: [{required: true, trigger: "blur"}]
                },
                newPageFormRules: {
                    name: [{required: true, trigger: "blur"}],
                    type: [{required: true, trigger: "blur"}],
                    platform: [{required: true, trigger: "blur"}],
                },
                statusOptionList: [],
                loading: false,
                current_page: {id:0},
            }
        },
        components: {
            BaseEditorHeader
        },
        props: {
            value: {
                type: Number,
                default: 60
            },
            minScale: {
                type: Number,
                default: 40
            },
            stepNum: {
                type: Number,
                default: 5
            }
        },
        created() {
            this.initData();
        },
        mounted() {

        },
        computed: {
            ...mapGetters(["storeinfo", "name", "avatar", "email", "token"]),
            UsersModel() {
                return this.$store.$db().model('users');
            },
            user() {
                return this.UsersModel.query().where('remember_token', getToken()).first();
            },
            loginStoreAble() {
                return (this.storeinfo && this.storeinfo.remember_token) ? true : false;
            },
            PagesModel() {
                return this.$store.$db().model('vue_editor_pages');
            },
            firstPage() {
                let editingPage = this.$store.$db().model('vue_editor_pages').query().with('itemsConfig').where('edit_status', 1).first();
                if (editingPage) {
                    return editingPage;
                }
                return this.$store.$db().model('vue_editor_pages').query().with('itemsConfig').first();
            },
            allPages() {
                return this.$store.$db().model('vue_editor_pages').all();
            },
            ItemsConfigModel() {
                return this.$store.$db().model('items_config');
            },
            loginLocalAble() {
                return (this.token && this.user) ? true : false;
            },
            platform: {
                get() {
                    return this.$route.name;
                },
                set(routerName) {
                    this.$router.replace({
                        name: routerName
                    });
                }
            },
            disabledMinus() {
                return this.value <= this.minScale;
            },
            disabledPlus() {
                return this.value >= 100;
            },
        },
        methods: {
            ...mapActions({
                loginStore: "user/loginStore",
                logoutStore: "user/logoutStore",
                loginLocal: "user/login",
                logoutLocal: "user/logout",
                localUserInfo: "user/getInfo",
            }),
            handlePlus() {
                const curScale = this.value + this.stepNum;
                this.emitUpdateScale(curScale);
            },
            handleMinus() {
                const curScale = this.value - this.stepNum;
                this.emitUpdateScale(curScale);
            },
            emitUpdateScale(curScale) {
                this.$emit('input', curScale);
                this.$emit('onUpdateScale', {
                    scale: curScale
                });
            },
            handleLocalForm() {
                this.$refs.localFormRef.validate(async valid => {
                    if (valid) {
                        let data = await this.loginLocal(this.storeForm);
                        let localUser = await this.localUserInfo();
                        // localStorage.setItem('user', JSON.stringify(adminUser));
                        this.initData();
                        this.localDialogVisible = false;
                    }
                });
            },
            handleLocalCommand(command) {
                this.logoutLocal();
                this.logoutStore();
            },
            closeLocalDialog() {
                this.$refs.localFormRef.clearValidate();
            },
            closeNewPageDialog() {
                this.$refs.newPageFormRef.clearValidate();
            },
            handleStoreForm() {
                this.$refs.storeFormRef.validate(async valid => {
                    if (valid) {
                        let {code, data} = await loginStore(this.storeForm);
                        let jsonData = {
                            "email": data.email,
                            "avatar": data.avatar,
                            "remember_token": data.remember_token,
                            "creator_id": data.creator_id
                        }; //离奇的类型转换问题，临时这样解决
                        if (code === 10000) {
                            this.loginStore(JSON.stringify(jsonData));
                            this.storeDialogVisible = false;
                        }
                    }
                });
            },
            handleCommand(command) {
                this.logoutStore();
            },
            closeDialog() {
                this.$refs.storeFormRef.clearValidate();
            },
            checkCapslock(e) {
                const {key} = e;
                this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
            },
            queryPagesList(query) {
                this.statusOptionList = this.allPages;
            },
            async initData() {
                if (getToken()) {
                    let adminUser = await this.UsersModel.fetchByToken();

                await this.PagesModel.index();   //需要确定时序，在通过API获取数据后再使用前端数据库中的数据
                this.PagesModel.commit((state) => {
                    state.fetching = true
                });
                this.current_page = this.firstPage;
                // this.ItemsConfigModel.fetchByToken();         //通过关联模型获取到了，无需单个表获取
                this.$emit('afterInitData', this.current_page); //需要确定时序，Editor数据初始化在API获取数据之后进行
                // console.log(this.ItemsConfigModel.all())
                }
            },
            selectPage() {
                this.$store.$db().model('vue_editor_pages').update({
                    where: (user) => {
                        return user.user_id === this.user.id
                    },
                    data: {edit_status: 0}
                });
                this.$store.$db().model('vue_editor_pages').update({      //用edit_status字段标识当前编辑中的页面
                    where: this.current_page.id,
                    data: {edit_status: 1}
                });
                this.current_page = this.$store.$db().model('vue_editor_pages').query().with('itemsConfig').where('id', this.current_page.id).first();
                this.PagesModel.selectPage(this.current_page.id);
                this.$emit('afterInitData', this.current_page);
            },
            handleNewPageForm() {
                this.$refs.newPageFormRef.validate(async valid => {
                    if (valid) {
                        this.newPageForm.user_id = this.user.id;
                        this.PagesModel.insert({data:this.newPageForm});
                        this.PagesModel.newPage(this.newPageForm);
                        this.newPageDialogVisible = false;
                    }
                });
            },
        }
    };
</script>

<style module>
    @import "demo-common/css/variable.css";

    .box {
        padding: 10px 2%;
        height: auto;
        background: var(--color-white);
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: 0 0 8px 1px rgba(0, 0, 0, .3);
    }

    .headerMenu {
        display: flex;
        align-items: center;
        justify-content: center;

    h1 {
        display: none;
        text-shadow: 0 0 40px #409EFF;
        font-size: 26px;
        text-transform: uppercase;
        z-index: 10;
    }

    }
    .selectPlatform {
        width: 100px;
        margin-right: 20px;
    }
</style>
